import '@/pages/components/StyleFile/btnStyle.less';
import { moneyFormat, nanoid16 } from '@/utils';
import { Radio } from 'antd';
import { Button } from 'devextreme-react';
import DropDownButton from 'devextreme-react/drop-down-button';
import SelectBox from 'devextreme-react/select-box';
import notify from 'devextreme/ui/notify';
import moment from 'moment';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import * as ReactDOMClient from 'react-dom/client';
import { useModel } from 'umi';
import { CpasIcon, DevPopup } from '~/public/cpas-ui';
import PageLoading from '../components/PageLoading';
import { columnsDataC, columnsDataM } from './columnData';
import SetClassiFication from './components/SetReclassiFiedItem';
import './index.less';
import InternalNbwl from './internalNbwl';
import PupopColumnAdjust from './PupopColumnAdjust';
import {
  deleteTable,
  getDisclosureApiData,
  getNbwltjData,
  getZLList,
  postFetchData,
  updateBB_ReportInter,
} from './service';
const XLSX = require('xlsx-js-style');

const InternalTran = React.forwardRef((props: any, ref: any) => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd, username } = (initialState?.curPart as API.CurPart) || {};
  const [nbwltjData, setNbwltjData] = useState<any[]>([]); // 内部往来账
  const [value, setValue] = useState<number>(1); // 当前期末 或者期初
  const [dataIdlist, setdataIdlist] = useState<[]>([]); // 年度
  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const NbwlRef = useRef<any>();
  const refPupopColumnAdjust = useRef<any>();
  const setBathJust = useRef<any>();
  const DelteRef = useRef<any>();
  const currentDataid = useRef<any>();
  const DeleteRef = useRef<any>();
  const sameData = useRef<any>();
  const addinnterData = useRef<any>();
  const AuditTableNameList = useRef<any>();

  /// 事件
  /**
   * 点击保存按钮
   */

  const onClickSaveBut = async () => {
    let no_data = true;
    const curDevTableRef: any = NbwlRef.current.getCurrentDevTable();

    const saveRequestData: any = []; // 曾删改变动的数据

    // 保存的逻辑有两个一个时，手动的增删改，由表格Chang触发的数据
    // 保存最新的自动获取的数据，先删除底稿获取的，在把最新的插入进去
    try {
      return await curDevTableRef.saveEditData().then(async (e: any) => {
        console.log(e, 'li');
        // 0 把excel添加的保存了
        let Auditlist_excel = nbwltjData.filter((a: any) => a.from_type === 'Excel' && a.data_type); // 自动获取底稿没有保存的数据
        Auditlist_excel = Auditlist_excel.map((a: any) => {
          let { data_type, LogicKey, ...newObj } = a;
          return newObj;
        });
        if (nbwltjData.length === 0) {
          notify(`当前项目为空 `, 'error', 2000);
          return 0;
        }
        if (Auditlist_excel.length) {
          if (Auditlist_excel.filter((a: any) => !(a.related && a.itemName)).length === 0) {
            no_data = false;
            await addData(Auditlist_excel);
          } else {
            notify(`保存失败！ 关联方和试算项目是必填项 `, 'error', 2000);
            return false;
          }
        }

        // 1，先把自动获取的数据保存了
        let Auditlist = nbwltjData.filter((a: any) => a.from_type === '底稿' && a.data_type); // 自动获取底稿没有保存的数据
        Auditlist = Auditlist.map((a: any) => {
          let { data_type, LogicKey, ...newObj } = a;
          return newObj;
        });
        if (Auditlist.length) {
          await deleteTable({
            dbname: dbname,
            tableName: 'BB_ReportIntercourse',
            data_id: currentDataid.current,
            from_type: '底稿',
          });
        }
        // 把自动获取的保存了
        if (Auditlist.length) {
          no_data = false;
          await addData(addDataMake({ arr: Auditlist }, '底稿'));
          NbwlRef.current.clearCurrentDevUpdateData();
        }

        // 2，在做变动的增删改执行
        let saveRequestData: any;
        const bathSetData = await setBathJust.current.getCurrentDevSaveData();

        if (bathSetData.length) {
          // 这个逻辑只为新增、、 其他的都是update
          saveRequestData = await NbwlRef.current.getCurrentDevUpdateData();
          saveRequestData = saveRequestData.map((a: any) => {
            let exait = bathSetData.filter(
              (b: any) => b.guid === a.guid && b.rowState === 'insert',
            );
            if (exait.length) {
              return {
                ...a,
                itemName: exait[0].itemName,
                KMMC: exait[0].KMMC,
                guid: a.guid,
                editDate: exait[0].editDate,
              };
            } else {
              return a;
            }
          });
        } else {
          //当前表变的数据
          saveRequestData = await NbwlRef.current.getCurrentDevUpdateData();
        }

        debugger;
        if (saveRequestData.length) {
          if (saveRequestData.filter((a: any) => !(a.related && a.itemName)).length === 0) {
            const res = await updateBB_ReportInter(dbname, saveRequestData);
            if (res.success) {
              notify(`保存成功！`, 'success', 2000);
              NbwlRef.current.clearCurrentDevUpdateData();
              no_data = false;
              // questNbwltjData(value);
            } else {
              notify(`保存失败！`, 'error', 2000);
            }
          } else {
            notify(`保存失败！ 关联方和试算项目是必填项 `, 'error', 2000);

            return false;
          }
        }
        // 弹窗表变得数据
        // 3. 把直接在批量设置的保存了,不在2中的 更新了 // 这的更新已经是保存到数据库里了，就是直接的更新，不用判断必填项了
        const bathSetDataUpdate = await setBathJust.current.getCurrentDevUpdateData();
        debugger;
        console.log(bathSetDataUpdate);
        if (bathSetDataUpdate.length) {
          no_data = false;

          await addData(bathSetDataUpdate.filter((a: any) => a.rowState === 'update')); // 保存修改
        }

        // debugger
        if (no_data) {
          notify(`暂无更改的数据！`, 'error', 2000);
          return false;
        }
        await setBathJust.current.clearDevUpdateData(); // 清空本此设置的数据
        return true;
      });
    } catch (error) {
      console.log('li', error);
    }
  };

  /**
   * 点击自动获取
   */
  const onClickgetAuditData = async () => {
    // 0 检验必填项
    setSpinLoad(true);
    //1，删除页面存储的底稿

    // 2，把新的获取的底稿更新到页面，点击保存时可以，把新获取的保存了

    // 测试case ： 多次点击自动获取，b：保存后点击自动获取
    const curDevTableRef: any = NbwlRef.current.getCurrentDevTable();
    // 如果有手动添加的先把手动添加没保存的保存了,在批量编辑模式下
    let ischeck = await curDevTableRef.hasEditData();
    if (ischeck) {
      setSpinLoad(false);
      return notify(`当前表单在编辑模式下，请先处理当前未保存的数据`, 'error', 2000);
    }
    let [AuditTableName] = await Promise.all([postFetchData('sjdg.Standname.get', { API: 1 })]);

    let matchList: any = AuditTableName.data.map((item: any) => AuditPaper({ apiName: item.API }));
    const other = await Promise.all(matchList);
    const [NbwltjData] = await Promise.all([questNbwltjData(value, currentDataid.current)]);
    //3，获取底稿
    if (!other.includes(false) && NbwltjData.ok) {
      // 排除上次自动获取没有保存的,排除手动添加或者
      // debugger
      let arr_dg = acountDataTransfer(other, AuditTableName.data, nbwltjData);
      // debugger
      // 加上用户 没保存的
      // const curDevData = await NbwlRef.current.getCurrentDevUpdateData();
      const copy_arr = [...NbwltjData.data.filter((a: any) => a.from_type !== '底稿'), ...arr_dg];

      setNbwltjData(copy_arr); // 转换并渲染数据
      notify(`自动获取完成，确认无误后，请点击保存 `, 'info', 2000);
    } else {
      notify(`从底稿获取内部往来的列表失败！`, 'error', 2000);
    }
    setSpinLoad(false);
  };

  /**
   *
   * @param e 期末，期初切换查询
   */
  const onRadioChange = async (e: number) => {
    setValue(e);
    InternalTran({ isQM: e, data_id: currentDataid.current });
  };

  /**
   *
   * @param e 年份点击
   */
  const onValueChanged = useCallback((e: any) => {
    console.log(e.previousValue);
    console.log(e.value);
    currentDataid.current = e.value;
    InternalTran({ isQM: value, data_id: e.value });
  }, []);
  /**
   *
   * @param e 导出
   */
  const onExportItemClick = async (e: any) => {
    console.log(e.itemData);
    if (e.itemData === '模板导出') {
      // Create workbook
      const wb = XLSX.utils.book_new();

      // Define data for both sheets
      let [acountListM, acountListC] = await Promise.all([questZLList(1), questZLList(2)]);
      debugger;

      buildExcel(
        wb,
        '内部往来',
        acountListM.data.filter((e: any) => e.show).map((item: any) => item),
        acountListC.data.filter((e: any) => e.show).map((item: any) => item),
      );

      /* show Save As dialog */
      // @ts-ignore
      const result = await window.electronComponents.showSaveDialog('xlsx', '内部往来模版');
      console.log(result);
      if (!result.canceled) {
        // let config= XLSX.writeFile(wb, result.filePath, { compression: true }); // 无法传导出路径，定义路径导出在主进程执行

        //@ts-ignore
        let config = await window.main.mainObject.XLSX_writeFile(
          wb.Sheets['内部往来'],
          result.filePath,
          '内部往来',
        );
        // XLSX.writeFile({Sheets:{[sheetName]:wb},SheetNames:[sheetName]}, pathFile, { compression: true })
        if (config) {
          notify(`导出成功！`, 'success', 2000);
        } else {
          notify(`导出失败！`, 'error', 2000);
        }
      }
    } else {
      //@ts-ignore
      const result = await window.electronComponents.openDialog({
        filters: [{ name: 'file', extensions: ['xlsx'] }],
      });

      /* get data as an ArrayBuffer */
      if (result.filePaths?.length) {
        const file = result.filePaths[0];
        const data = await (await fetch(file)).arrayBuffer();

        /* parse and load first worksheet */
        const wb = XLSX.read(data);
        try {
          let [acountListM1, acountListC1] = await Promise.all([questZLList(1), questZLList(2)]);
          let accountlistKey = [
            ...acountListM1?.data?.map((a: any) => a.key),
            ...acountListC1?.data?.map((b: any) => b.key),
          ].join('');
          let arr = parseExcel(wb, accountlistKey);
          if (arr) {
            setBathJust.current.show({
              leftItemList: arr.map((a: any) => {
                return { ...a, from_type: 'Excel', data_type: 1, guid: nanoid16() };
              }),
              DataId: currentDataid.current,
              Sys_AuditTableName: [],
              db_math: 'insert',
            });
            return;
            debugger;
          }
        } catch (error) {
          console.log(error);
        }
      }
    }
  };

  /**
   *  add 数据 手动单个，excel导入，底稿导入
   * @param params
   *
   */
  const addData = async (params: any) => {
    const res = await updateBB_ReportInter(dbname, params);
    if (res.success) {
      notify(`保存成功！`, 'success', 2000);
      InternalTran({ isQM: value, data_id: currentDataid.current });
    } else {
      notify(`保存失败！`, 'error', 2000);
    }
  };

  const addDataMake = (params: any, from_type: string) => {
    let arr: any = [];
    params.arr.map((item: any, index: number) => {
      let temo = {
        guid: nanoid16(),
        rowState: 'insert',
        updateFlag: 1,
        editDate: moment().format('YYYY-MM-DD HH:mm:ss'),
        editUser: username,
        data_id: currentDataid.current,
        from_type: from_type, //'Excel'
      };

      arr.push({ ...temo, ...item });
    });
    return arr;
  };
  /**
   *
   *
   */
  const onClickDelete = async () => {
    DeleteRef.current.show({
      title: '提示',
      okCallback: () => {
        deleteAllRow();
        InternalTran({ isQM: value, data_id: currentDataid.current });
      },
    });
  };
  /**
   *
   * @param params
   *
   *
   */
  const deleteAllRow = (from_type?: string) => {
    let dd: any = {
      dbname: dbname,
      tableName: 'BB_ReportIntercourse',
      data_id: currentDataid.current,
    };
    if (from_type) {
      dd = { ...dd, from_type };
    }
    deleteTable(dd); // 多行删除，in 如何实现
  };
  /// 查询函数 点击侧边进入

  const InternalTran = async (params?: any) => {
    setSpinLoad(true);

    let [dgnd_list] = await Promise.all([
      postFetchData('home.zcbfAuditSection', { zcbfid: dbname }),
    ]);
    // AuditTableNameList.current = AuditTableName

    if (dgnd_list.ok && dgnd_list.data.length) {
      //currentDataid.current = dgnd_list.data[dgnd_list.data.length-1].Data_ID
      setdataIdlist(
        dgnd_list.data.map((item: any) => {
          return { ID: item.Data_ID };
        }),
      );
    } else {
      notify(`底稿年度无法展示！`, 'error', 2000);
    }

    const [ZLList, NbwltjData] = await Promise.all([
      questZLList(params.isQM),
      questNbwltjData(params.isQM, params.data_id),
    ]);

    // console.log(ZLList, other)
    if (NbwltjData.ok) {
      let copy_arr: any = [...NbwltjData.data];

      copy_arr = copy_arr.sort((a: any, b: any) => {
        return (new Date(b.editDate) as any) - (new Date(a.editDate) as any);
      });

      setNbwltjData(copy_arr);
      // 转换并渲染数据
      // return res.data;
      const colTempData = params?.isQM === 2 ? columnsDataC : columnsDataM;
      dataTransfer(ZLList.data, colTempData); // 转换数据，并渲染页面
    } else {
      notify(`获取内部往来的列表失败！`, 'error', 2000);
    }
    setSpinLoad(false);
  };
  /**
   *
   * @param params  批量获取底稿数据
   */
  const AuditPaper = async (params: { apiName: string }) => {
    // name: '108.02.CL_AR_MXB', // 应收账款明细表
    // name : '116.02.CL_OtherARK_MXB', // 其他应收账款明细表
    return getDisclosureApiData(params.apiName, dbname, currentDataid.current);
  };

  /**
   *
   * @param selectID 手动内部往来账查询
   */
  const questNbwltjData = async (selectID: number = 1, data_id: string) => {
    const isQM = selectID === 1;
    const res: any = getNbwltjData({
      dbname,
      isQM,
      data_id: data_id,
    });
    return res;
  };

  /**
   * 账龄查询
   */
  const questZLList = async (selectID: number = 1) => {
    const isQM = selectID === 1;
    const res: any = getZLList({
      dbname,
      isQM,
    });
    return res;
  };

  /**
   * 数据转换函数
   */
  const dataTransfer = (data: any, P: any) => {
    const realCol = data.map((item: any) => {
      const tempCol = {
        caption: item.title,
        dataField: item.key,
        dataType: 'number',
        // dataTypeCustom: "money-number",
        width: 140,
        editorOptions: {
          format: { type: 'decimal', currency: 'CNY', precision: 2 },
        },
        alignment: 'right',
        cellTemplate: (cellElement: any, cellInfo: any) => {
          const { data, rowIndex } = cellInfo;
          return ReactDOMClient.createRoot(cellElement).render(
            <>
              {data[item.key] === 0 || data[item.key] === null ? '' : moneyFormat(data[item.key])}
            </>,
          );
        },
      };
      return tempCol;
    });
    P.forEach((item: any) => {
      if (item.caption === '审定账龄') {
        item.columns = realCol;
        return item;
      }
      if (item.caption === '期末审定原值' || item.caption === '期初审定原值') {
        item.cellTemplate = (cellElement: any, cellInfo: any) => {
          const { data, rowIndex } = cellInfo;
          return ReactDOMClient.createRoot(cellElement).render(
            <>
              {data[item.dataField] === 0 || data[item.dataField] === null
                ? ''
                : moneyFormat(data[item.dataField])}
            </>,
          );
        };
        return item;
      }
      return item;
    });
    NbwlRef.current.updateSetData(P);
  };

  const acountDataTransfer = (data: any[], AuditTableName: any, nbwltjData: any) => {
    let result: any = [];
    data.forEach((i: any, includes: number) => {
      if (i.data.length) {
        let items = i.data.filter((a: any) => a.关联方类型 === '合并范围内关联方');

        items.map((item: any) => {
          console.log(nbwltjData, item.主键 + AuditTableName[includes].GUID);
          // 多次自动获取只把新增的获取回来，
          if (1) {
            result.push({
              // ...item,
              data_type: 1, // 标识自动获取为保存的
              DG_NAME: AuditTableName[includes].StandardSheetName,
              guid: nanoid16(),
              LogicKey: item.主键 + AuditTableName[includes].API,
              from_type: '底稿',
              related: item.审定债务人名称 || item.审定债权人名称,
              KMMC: AuditTableName[includes].KMMC,
              QMSDYZ:
                item.审定数 ||
                item.应收账款余额审定数 ||
                item.其他应收款余额期末审定数 ||
                item.期末审定数,
              QCSDYZ: item.期初审定余额 || item.期初审定,
              itemName: AuditTableName[includes].ReportItemName,
              KXXZ: item.款项性质,
              PreHY1: item['期初审定账龄|1-6月'],
              PreHY2: item['期初审定账龄|7-12月'],
              PreY1: item['期初审定账龄|1年以内'],
              PreY2: item['期初审定账龄|1年以上'],
              PreY3: item['期初审定账龄|1-2年'],
              PreY4: item['期初审定账龄|2年以上'],
              PreY5: item['期初审定账龄|2-3年'],
              PreY6: item['期初审定账龄|3年以上'],
              PreY7: item['期初审定账龄|3-4年'],
              PreY8: item['期初审定账龄|4年以上'],
              PreY9: item['期初审定账龄|4-5年'],
              PreY10: item['期初审定账龄|5 年以上'],

              PreM1: item['期初审定账龄|1个月'],
              PreM2: item['期初审定账龄|2个月'],
              PreM3: item['期初审定账龄|3个月'],
              PreM4: item['期初审定账龄|4个月'],
              PreM5: item['期初审定账龄|5个月'],
              PreM6: item['期初审定账龄|6个月'],
              PreM7: item['期初审定账龄|7个月'],
              PreM8: item['期初审定账龄|8个月'],
              PreM9: item['期初审定账龄|9个月'],
              PreM10: item['期初审定账龄|10个月'],
              PreM11: item['期初审定账龄|11个月'],
              PreM12: item['期初审定账龄|12个月'],
              PreQ1: item['期初审定账龄|1-3月'],
              PreQ2: item['期初审定账龄|4-6月'],
              PreQ3: item['期初审定账龄|7-9月'],
              PreQ4: item['期初审定账龄|10-12月'],

              M1: item['期末审定账龄|1个月'],
              M2: item['期末审定账龄|2个月'],
              M3: item['期末审定账龄|3个月'],
              M4: item['期末审定账龄|4个月'],
              M5: item['期末审定账龄|5个月'],
              M6: item['期末审定账龄|6个月'],
              M7: item['期末审定账龄|7个月'],
              M8: item['期末审定账龄|8个月'],
              M9: item['期末审定账龄|9个月'],
              M10: item['期末审定账龄|10个月'],
              M11: item['期末审定账龄|11个月'],
              M12: item['期末审定账龄|12个月'],
              Q1: item['期末审定账龄|1-3月'],
              Q2: item['期末审定账龄|4-6月'],
              Q3: item['期末审定账龄|7-9月'],
              Q4: item['期末审定账龄|10-12月'],
              HY1: item['期末审定账龄|1-6月'],
              HY2: item['期末审定账龄|7-12月'],
              Y1: item['期末审定账龄|1年以内'],
              Y2: item['期末审定账龄|1年以上'],
              Y3: item['期末审定账龄|1-2年'],
              Y4: item['期末审定账龄|2年以上'],
              Y5: item['期末审定账龄|2-3年'],
              Y6: item['期末审定账龄|3年以上'],
              Y7: item['期末审定账龄|3-4年'],
              Y8: item['期末审定账龄|4年以上'],
              Y9: item['期末审定账龄|4-5年'],
              Y10: item['期末审定账龄|5年以上'],
            });
          }
        });
      }
    });

    // console.log(result, data);
    return result;
  };

  const buildExcel = (wb: any, e: any, pdata: any, QcData: any) => {
    let arrayQm = ['期末审定账龄'];
    arrayQm = arrayQm.concat(new Array(pdata.length - 1).fill(''));
    let arrayQc = ['期初审定账龄'];
    arrayQc = arrayQc.concat(new Array(QcData.length - 1).fill(''));
    const data = [
      [
        '关联方',
        '试算项目',
        '科目名称',
        '款项性质',
        `期末审定原值`,
        ...arrayQm,
        ...arrayQc,
        '期初审定原值',
        '坏账准备',
      ],
      ['', '', '', '', ``, ...pdata.map((a) => a.title), ...QcData.map((a) => a.title), '', ''],
    ];

    // Define style for headers
    const headerStyle = {
      alignment: { horizontal: 'center', vertical: 'center' },
      font: { bold: true },
      fill: { fgColor: { rgb: 'F0F0F0' } },
      // wpx: 100 ,
      wch: 100,
      // width: 400 ,
      border: {
        top: { style: 'thin', color: { rgb: 'F0F0F0' } },
        bottom: { style: 'thin', color: { rgb: 'F0F0F0' } },
        left: { style: 'thin', color: { rgb: 'F0F0F0' } },
        right: { style: 'thin', color: { rgb: 'F0F0F0' } },
      },
    };

    // Apply styles and create sheet data
    const sheetData = data.map((row, rowIndex) => {
      return row.map((cell, colIndex) => {
        let cellData = { v: cell, s: {} };
        if (rowIndex <= 1) {
          cellData.s = headerStyle;
          if (rowIndex === 1 && colIndex > 4) {
            if (rowIndex === 1 && colIndex > 4 + pdata.length) {
              QcData.forEach((e: any, index: any) => {
                if (cell === e.title) {
                  if (!cellData['c']) cellData['c'] = [];
                  cellData['c'].push({ a: 'SheetJS', t: e.key, T: false });
                  // cellData['c'].hidden = true;
                }
              });
            } else {
              pdata.forEach((e: any, index: any) => {
                if (cell === e.title) {
                  if (!cellData['c']) cellData['c'] = [];
                  cellData['c'].push({ a: 'SheetJS', t: e.key, T: false });
                  // cellData['c'].hidden = true;
                }
              });
            }
            // cellData['c'].hidden = true;
          }
        }
        return cellData;
      });
    });

    const wsEnd = XLSX.utils.aoa_to_sheet(sheetData);

    wsEnd['!merges'] = [
      { s: { r: 0, c: 0 }, e: { r: 1, c: 0 } }, // Merge cells A2:A4
      { s: { r: 0, c: 1 }, e: { r: 1, c: 1 } }, // Merge cells B2:B4
      { s: { r: 0, c: 2 }, e: { r: 1, c: 2 } }, // Merge cells B2:B4
      { s: { r: 0, c: 3 }, e: { r: 1, c: 3 } }, // Merge cells B2:B4
      { s: { r: 0, c: 4 }, e: { r: 1, c: 4 } }, // Merge cells B2:B4
      { s: { r: 0, c: 5 }, e: { r: 0, c: 4 + pdata.length } }, // Merge cells B2:B4
      { s: { r: 0, c: 5 + pdata.length }, e: { r: 0, c: 4 + pdata.length + QcData.length } }, // Merge cells B2:B4
      {
        s: { r: 0, c: 5 + pdata.length + QcData.length },
        e: { r: 1, c: 5 + pdata.length + QcData.length },
      }, // Merge cells B2:B4  坏账金额
      {
        s: { r: 0, c: 6 + pdata.length + QcData.length },
        e: { r: 1, c: 6 + pdata.length + QcData.length },
      }, // Merge cells B2:B4  坏账金额
    ];
    wsEnd['!cols'] = [{ wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }];

    // Add sheets to workbook
    XLSX.utils.book_append_sheet(wb, wsEnd, '内部往来');
  };

  /**
   *  解析excel
   */
  const parseExcel = (wb: any, accountlistKey?: any, dblist?: []) => {
    const ws = wb.Sheets[wb.SheetNames[0]];
    // const head_data = XLSX.utils.sheet_to_json(ws, { range: 0 })
    let col_list: any[] = [];

    var ref = XLSX.utils.decode_range(ws['!ref']);
    for (var R = 0; R <= ref.e.r; ++R)
      for (var C = 0; C <= ref.e.c; ++C) {
        var addr = XLSX.utils.encode_cell({ r: R, c: C });
        if (!ws[addr] || !ws[addr].c) continue;
        var comments = ws[addr].c;
        if (!comments.length) continue;
        var threaded = !!comments[0].T;
        var msg = comments.map((c: any) => c.t).join(threaded ? '\n' : '');

        if (msg.length > 0) {
          col_list.push(msg);
        }
        console.log(comments, msg);
        //  html.push(`${n}:${addr}:${+!!threaded}:${msg}`);
      }

    if (col_list.join('') === accountlistKey) {
      console.log(ws, col_list, 'ssssssss');

      return XLSX.utils.sheet_to_json(ws, {
        header: ['related', 'itemName', 'KMMC', 'KXXZ', 'QMSDYZ', ...col_list, 'QCSDYZ', 'HZZB'],
        range: 2,
      });
    } else {
      return notify(
        '导入模板账龄不匹配，请从新导出模板制作数据,或者安装模板设置账龄',
        'error',
        2000,
      );
    }
  };
  /**
   * 首次进入，批量并发查询
   */
  useEffect(() => {
    if (dbname) {
      currentDataid.current = sjnd;
      InternalTran({ isQM: 1, data_id: sjnd });
    }
  }, []);
  return (
    <div className="InternalTranBox">
      <div className="formsHeader">
        <div className="formTitle">内部往来统计</div>
      </div>
      <div className="statisticsBoxbtnsTools">
        <Button
          type="default"
          className="defaultBtn"
          text="保存"
          onClick={async () => {
            if (await onClickSaveBut()) {
              await InternalTran({ isQM: value, data_id: currentDataid.current });
            }
          }}
        />

        <Button
          type="default"
          className="defaultBtn"
          text="增加"
          onClick={() => {
            const curDevTableRef: any = NbwlRef.current.getCurrentDevTable();
            curDevTableRef.addRow();
          }}
        />
        <Button
          type="default"
          className="defaultBtn"
          text="自动获取"
          onClick={() => {
            onClickgetAuditData();
          }}
        />

        <Button
          type="normal"
          stylingMode="outlined"
          className="defaultBtn"
          text="账龄设置"
          onClick={() => {
            refPupopColumnAdjust.current.showPupop(value);
          }}
        />
        <DropDownButton
          style={{ height: '34px', Width: '100px', marginLeft: '8px', marginRight: '8px' }}
          text="导出导入"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={onExportItemClick}
          items={['往来导入', '模板导出']}
        />
        <Button
          type="normal"
          stylingMode="outlined"
          className="defaultBtn"
          text="批量对应设置"
          onClick={async () => {
            // 传的数据是 多页的
            let [AuditTableName] = await Promise.all([
              postFetchData('sjdg.Standname.get', { API: 1 }),
            ]);
            if (AuditTableName?.data?.length) {
              // 不批量设置没保存的
              setBathJust.current.show({
                leftItemList: nbwltjData.filter((a: any) => 1),
                DataId: currentDataid.current,
                Sys_AuditTableName: AuditTableName.data,
              });
            } else {
              notify('获取系统默认标准页对应关系表失败', 'error', 2000);
            }
          }}
        />

        <Button
          className="defaultReloadBtnWhite"
          render={() => <CpasIcon type="icon-delete" sz="lg" style={{ marginLeft: 20 }} />}
          onClick={() => {
            onClickDelete();
          }}
        />

        <Button
          className="defaultReloadBtnWhite"
          render={() => <CpasIcon type="icon-refresh" fontSize={16} />}
          onClick={() => {
            NbwlRef.current.clearCurrentDevUpdateData();
            InternalTran({ isQM: value, data_id: currentDataid.current });
          }}
        />
      </div>
      <PupopColumnAdjust
        ref={refPupopColumnAdjust}
        reloadDevTable={() => {
          onRadioChange(value);
        }}
      />

      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'left',
          marginBottom: 15,
          padding: '0 5px',
        }}
      >
        <div
          style={{
            whiteSpace: 'nowrap',
            width: '200px',
            display: 'flex',
            marginRight: 10,
            alignItems: 'center',
          }}
        >
          年度：
          <SelectBox
            dataSource={dataIdlist}
            displayExpr={'ID'}
            valueExpr="ID"
            defaultValue={sjnd}
            onValueChanged={(e: any) => {
              onValueChanged(e);
            }}
          ></SelectBox>
        </div>

        <Radio.Group
          onChange={(e) => {
            onRadioChange(e.target.value);
          }}
          value={value}
        >
          <Radio value={1}>期末</Radio>
          <Radio value={2}>期初</Radio>
        </Radio.Group>
        {/* <span style={{ color: 'red' }}>
                    提示：数据来源于结构化底稿，若需修改，请先修改底稿
                </span> */}
      </div>
      {/* {spinLoad && <SpinLoading loadString="" />} */}
      <PageLoading isOpen={spinLoad} isMaskClose={false} content={''} width={200} />
      <SetClassiFication
        addData={addDataMake}
        setNbwltjData={setNbwltjData}
        DataId={currentDataid.current}
        isQC={value === 1 ? '期末' : '期初'}
        ref={setBathJust}
        refresh={() => InternalTran({ isQM: value, data_id: currentDataid.current })}
      />
      <div style={{ width: '100%', height: 'calc(100% - 95px)' }}>
        <InternalNbwl
          DevData={nbwltjData}
          ref={NbwlRef}
          data_id={currentDataid.current}
          setNbwltjData={setNbwltjData}
        />
        <DevPopup.Default ref={DelteRef} width={80} height={220}>
          {() => {
            return (
              <>
                {' '}
                <div> 是否继续导入？ </div>
                <b></b>
                {sameData.current}
              </>
            );
          }}
        </DevPopup.Default>

        <DevPopup.Default ref={DeleteRef} width={80} height={220}>
          {() => {
            return (
              <>
                {' '}
                <div> 是否全部删除？ </div>
                <b></b>
                {sameData.current}
              </>
            );
          }}
        </DevPopup.Default>
      </div>
    </div>
  );
});

export default InternalTran;
